package com.zeratul.common.pool.config;

import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.pool.config.thread.CoreThreadPoolConfig;
import com.zeratul.common.pool.config.thread.CpuThreadPoolConfig;
import com.zeratul.common.pool.config.thread.DelayThreadPoolConfig;
import com.zeratul.common.pool.utils.ThreadUtils;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Import;

import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

@AutoConfiguration
@Import({
        CoreThreadPoolConfig.class,
        DelayThreadPoolConfig.class,
        CpuThreadPoolConfig.class
})
@Slf4j
public class ZeratulPoolAutoConfiguration {

    /**
     * 获取相关线程池对象
     */
    @Autowired(required = false)
    private Map<String, Executor> executorMap;


    /**
     * 线程池销毁事件
     */
    @PreDestroy
    public void destroy() {
        //获取线程池的Bean
        if (ObjectUtil.isEmpty(executorMap)) {
            return;
        }
        //循环关闭线程池
        executorMap.forEach((key, value) -> {
            try {
                log.info("【关闭线程池】正在关闭线程池 - {} 线程池类型：{}", key, value.getClass().getName());
                if (value instanceof ExecutorService executorService) {
                    ThreadUtils.shutdownAndAwaitTermination(executorService);
                }
            } catch (Exception e) {
                log.error("【关闭线程池】异常", e);
            }
        });
    }
}
